<template>
  <div class="cesium-container">
    <div id="cesiumContainer" ref="cesiumContainer" class="container" />
    <div class="globe-slider" v-if="isUndergroundModel">
      <el-slider vertical :step="stepSlide" height="200px" v-model="globeSlider" @input="globeSliderChange"></el-slider>
    </div>
    <div class="component-list">
      <div v-for="item in componentList" :key="item.busType">
        <transition name="fade-transform" mode="out-in">
          <!-- !isShowThree &&  -->
          <component :is="item.component" v-show="item.isShow" :widget-config="item.config" :cesium-width="cesiumWidth" />
        </transition>
      </div>
    </div>
  </div>
</template>

<script>
import DxCommonUtils from "@/utils/cesiumDxUtils/common3D";
import widgetsOptions from "@/cesiumWidgets/widgetsOptions";
import { mapState } from "vuex";

export default {
  name: "CesiumMap",
  props: {
    cesiumWidth: {
      type: Number,
      default: 0,
    },
  },
  computed: {
    ...mapState({
      isShowThree: (state) => state.app.isShowThree, // threejs 开启关闭
      isUndergroundModel: (state) => state.app.isUndergroundModel, // threejs 开启关闭
    }),
  },
  data() {
    return {
      componentList: widgetsOptions,
      globeSlider: 50,
      stepSlide: 1,
    };
  },
  mounted() {
    this.initMap();
    //  监听事件 cesiumBusEvent
    this.$bus.on("cesiumBusEvent", this.widgetsChange);
  },
  beforeDestroy() {
    // this.viewer = null;
    this.$bus.emit("mapCreated", null);
  },

  methods: {
    globeSliderChange() {
      // this.globeSlider = this.globeSlider > 80 ? 100 : this.globeSlider;
      if (this.globeSlider > 80) {
        viewer.scene.globe.baseColor = new Cesium.Color(0, 0, 0.1, 1.0);
        viewer.scene.globe.depthTestAgainstTerrain = true;
        viewer.scene.screenSpaceCameraController.enableCollisionDetection = false;
        viewer.scene.globe.translucency.enabled = false;
      } else {
        this.$store.commit("app/updataUndergroundModel", true);
        viewer.scene.globe.depthTestAgainstTerrain = true;
        viewer.scene.globe.translucency.frontFaceAlphaByDistance =
          new Cesium.NearFarScalar(400.0, 0.0, 800.0, 1.0);
        viewer.scene.globe.translucency.enabled = true;
        viewer.scene.globe.baseColor = new Cesium.Color(0, 0, 0, 0);
      }
      var alpha = Number(this.globeSlider / 100);
      alpha = alpha.toFixed(1);
      // alpha = Cesium.Math.clamp(alpha, 0.0, 1.0);
      // viewer.scene.globe.translucency.frontFaceAlphaByDistance.nearValue =
      //   alpha;
      // viewer.scene.globe.translucency.frontFaceAlphaByDistance.farValue = false
      //   ? 1.0
      //   : alpha;

      if (viewer.imageryLayers) {
        for (var i = 0; i < viewer.imageryLayers.length; i++) {
          viewer.imageryLayers.get(i).alpha = alpha;
        }
      }
      //刷新全部的影像切片
      // viewer.scene.globe._surface.invalidateAllTiles();
    },
    // 初始化地图
    async initMap() {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiI0MmM1OWE5OS04ZDAwLTRjYjctOTE4OS1jZDU3Yzg1YjMyNTUiLCJpZCI6NjA1NzksImlhdCI6MTYyNTE5MzIwN30.E1GPZVSqFShdHOqt79w433mnnggFbU0AIj35tfDyK4Y";
      window.viewer = this.viewer = new this.Cesium.Viewer("cesiumContainer", {
        allowTextureFilterAnisotropic: true,
        animation: false, // 是否创建动画小器件，左下角仪表
        baseLayerPicker: false, // 是否显示图层选择器
        fullscreenButton: false, // 是否显示全屏按钮
        geocoder: false, // 是否显示geocoder小器件，右上角查询按钮
        homeButton: false, // 是否显示Home按钮
        infoBox: false, // 是否显示信息框
        sceneModePicker: false, // 是否显示3D/2D选择器
        selectionIndicator: false, // 是否显示选取指示器组件
        timeline: false, // 是否显示时间轴
        navigationHelpButton: false, // 是否显示右上角的帮助按钮
        // scene3DOnly: true, // 如果设置为true，则所有几何图形以3D模式绘制以节约GPU资源
        // clock: new Cesium.Clock(), // 用于控制当前时间的时钟对象
        selectedImageryProviderViewModel: undefined, // 当前图像图层的显示模型，仅baseLayerPicker设为true有意义
        // imageryProviderViewModels:
        //   Cesium.createDefaultImageryProviderViewModels(), // 可供BaseLayerPicker选择的图像图层ProviderViewModel数组
        // selectedTerrainProviderViewModel: undefined, // 当前地形图层的显示模型，仅baseLayerPicker设为true有意义
        // terrainProviderViewModels:
        //   Cesium.createDefaultTerrainProviderViewModels(), // 可供BaseLayerPicker选择的地形图层ProviderViewModel数组
        // imageryProvider: new this.Cesium.UrlTemplateImageryProvider({
        //   url: "https://webst02.is.autonavi.com/appmaptile?style=6&x={x}&y={y}&z={z}",
        // }),
        imageryProvider: new Cesium.WebMapTileServiceImageryProvider({
          url: "http://t0.tianditu.com/img_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=img&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&tk=fbeb8321aa160bc822ac170257a93156",
          layer: "tiandituImg",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "tiandituImg",
          show: true,
          maximumLevel: 19,
        }),


        imageryProviderViewModels:
          Cesium.createDefaultImageryProviderViewModels(), // 可供BaseLayerPicker选择的图像图层ProviderViewModel数组
        selectedTerrainProviderViewModel: undefined, // 当前地形图层的显示模型，仅baseLayerPicker设为true有意义

        showRenderLoopErrors: false, // 如果设为true，将在一个HTML面板中显示错误信息
        automaticallyTrackDataSourceClocks: true,
        // terrainProvider: new Cesium.EllipsoidTerrainProvider(),
        // terrainProvider: new Cesium.CesiumTerrainProvider({
        //   //地质开挖必须是cesium提供的地形
        //   // url: 'https://lab.earthsdk.com/terrain/4676cbcd5a7b93b0e7f4ab6f6a4f8fec', //  Cesium.IonResource.fromAssetId(1),
        //   url: "https://lab.earthsdk.com/terrain/577fd5b0ac1f11e99dbd8fd044883638", //  Cesium.IonResource.fromAssetId(1),
        //   requestVertexNormals: true, //顶点法线效果
        //   requestWaterMask: true, //水效果
        // }),


        // skyBox: new Cesium.SkyBox({
        //   sources: {
        //     positiveX: "Cesium-1.7.1/Skybox/px.jpg",
        //     negativeX: "Cesium-1.7.1/Skybox/mx.jpg",
        //     positiveY: "Cesium-1.7.1/Skybox/py.jpg",
        //     negativeY: "Cesium-1.7.1/Skybox/my.jpg",
        //     positiveZ: "Cesium-1.7.1/Skybox/pz.jpg",
        //     negativeZ: "Cesium-1.7.1/Skybox/mz.jpg",
        //   },
        // }), // 用于渲染星空的SkyBox对象
        // fullscreenElement: document.body, // 全屏时渲染的HTML元素,
        // useDefaultRenderLoop: true, // 如果需要控制渲染循环，则设为true
        // targetFrameRate: undefined, // 使用默认render loop时的帧率
        showRenderLoopErrors: false, // 如果设为true，将在一个HTML面板中显示错误信息
        automaticallyTrackDataSourceClocks: true, // 自动追踪最近添加的数据源的时钟设置
        // contextOptions: undefined, // 传递给Scene对象的上下文参数（scene.options）
        // sceneMode: Cesium.SceneMode.SCENE3D, // 初始场景模式
        // mapProjection: new Cesium.WebMercatorProjection(), // 地图投影体系
        // dataSources: new Cesium.DataSourceCollection(),
        // requestRenderMode: true,
        terrainShadows: Cesium.ShadowMode.RECEIVE_ONLY, //地质接收阴影
        contextOptions: {
          webgl: {
            alpha: true,
            depth: true,
            stencil: true,
            antialias: true,
            premultipliedAlpha: true,
            // 通过canvas.toDataURL()实现截图需要将该项设置为true
            preserveDrawingBuffer: true,
            failIfMajorPerformanceCaveat: true,
          },
        },
      });

      //    {
      //     id: 2,
      //     name: '矢量底图',
      //     img: require('../../assets/img/baseLayer (2).png'),
      //     imageryProvider:
      // new Cesium.WebMapTileServiceImageryProvider({
      //     url: "http://t0.tianditu.gov.cn/vec_c/wmts?tk=fbeb8321aa160bc822ac170257a93156",
      //     layer: "tiandituImg",
      //     style: "default",
      //     format: "image/jpeg",
      //     tileMatrixSetID: "tiandituImg",
      //     show: true,
      //     maximumLevel: 18
      // })
      // },

      //      viewer.imageryLayers.addImageryProvider(img);
      var helpercb = new Cesium.EventHelper();
      await helpercb.add(
        this.viewer.scene.globe.tileLoadProgressEvent,
        function (event) {
          if (event == 0) {
            // console.log("这个是加载最后一个矢量切片的回调");
          }
        }
      );
      // 4676cbcd5a7b93b0e7f4ab6f6a4f8fec
      //bc52df9b0d3492bea63c82cd4d5ba069
      // fbeb8321aa160bc822ac170257a93156

      this.viewer.imageryLayers.addImageryProvider(
        new Cesium.WebMapTileServiceImageryProvider({
          //影像注记
          url: "http://t{s}.tianditu.com/cia_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cia&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default.jpg&tk=fbeb8321aa160bc822ac170257a93156",
          subdomains: ["0", "1", "2", "3", "4", "5", "6", "7"], // ["t0", "t1", "t2", "t3", "t4", "t5", "t6", "t7"],
          layer: "tdtCiaLayer",
          style: "default",
          format: "image/jpeg",
          tileMatrixSetID: "GoogleMapsCompatible",
          show: true,
        })
      );

      this.viewer._cesiumWidget._creditContainer.style.display = "none"; //	去除版权信息
      //
      //地质开挖不能有深度测试，有深度测试会被遮盖
      this.viewer.scene.globe.depthTestAgainstTerrain = true;

      // var aaa = new Cesium.FrameRateMonitor({ scene: this.viewer.scene });

      // this.$bus.emit("mapCreated", this.viewer);

      // 创建监听cesium的基本属性信息
      // this.cameraChangedEventListener();

      //监听鼠标位置，获取经纬度
      this.mouseMoveListener();
      // 初始化飞入指定位置
      DxCommonUtils.cameraFlyTo({});
    },
    // 创建相机位置变动的监听
    cameraChangedEventListener() {
      this.viewer.camera.changed.addEventListener((percentage) => {
        const heading = this.viewer.scene.camera.heading.toFixed(6);
        const position = DxCommonUtils.getCenterPosition();
        this.$store.commit("cesiumBaseInfo/SET_BASE_CESIUM_INFO", {
          lon: position.lon,
          lat: position.lat,
          height: position.height,
          heading: heading,
        });
      });
    },
    mouseMoveListener() {
      var MouseHeight = 0;
      var lon, lat, cartographic1;
      let handlers = new Cesium.ScreenSpaceEventHandler(
        viewer.scene._imageryLayerCollection
      );
      // 获取相机的海拔高度作为视角高度/km
      handlers.setInputAction((event) => {
        //获取相机射线
        const ray = viewer.scene.camera.getPickRay(event.endPosition);
        //根据射线和场景求出在球面中的笛卡尔坐标
        const position1 = viewer.scene.globe.pick(ray, viewer.scene);
        //获取该浏览器坐标的顶部数据
        const feature = viewer.scene.pick(event.endPosition);
        if (feature == undefined && position1) {
          cartographic1 =
            Cesium.Ellipsoid.WGS84.cartesianToCartographic(position1);
          lon = Cesium.Math.toDegrees(cartographic1.longitude);
          lat = Cesium.Math.toDegrees(cartographic1.latitude);
          MouseHeight = 0;
        } else {
          let cartesian = viewer.scene.pickPosition(event.endPosition);
          if (Cesium.defined(cartesian)) {
            //如果对象已定义，将度转为经纬度
            let cartographic = Cesium.Cartographic.fromCartesian(cartesian);
            lon = Cesium.Math.toDegrees(cartographic.longitude);
            lat = Cesium.Math.toDegrees(cartographic.latitude);
            MouseHeight = cartographic.height; //模型高度
          }
        }
        // 获取相机的高度
        let cameraHeight = Math.ceil(viewer.camera.positionCartographic.height);

        this.$store.commit("cesiumBaseInfo/SET_BASE_CESIUM_INFO", {
          lon: lon,
          lat: lat,
          height: cameraHeight,
          // heading: heading,
        });
      }, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
    },
    // widgets 事件监听 控制widget的显隐
    widgetsChange(type) {
      const obj =
        this.componentList.find((item) => item.busType === type) || null;
      if (obj && obj.longDisplay) {
        obj.isShow = !obj.isShow;
        return;
      }
      this.componentList.forEach((item) => {
        if (item.longDisplay) {
          return;
        }
        if (item.busType === type) {
          item.isShow = !item.isShow;
        } else {
          item.isShow = false;
        }
      });
      // const obj =
      //   this.componentList.find((item) => item.busType === type) || null;
      // obj.isShow = !obj.isShow;
      // if (!obj.longDisplay) {
      // }
    },
  },
  watch: {
    isShowThree() {
      // const obj = this.componentList.find(
      //   (item) => item.title === "CesiumVewerToolbar"
      // );
      // if (this.isShowThree) {
      //   obj.isShow = false;
      // } else {
      //   obj.isShow = true;
      // }
    },
    isUndergroundModel() {
      if (!this.isUndergroundModel) {
        this.globeSlider = 100;
        this.globeSliderChange();
        viewer.scene.screenSpaceCameraController.enableCollisionDetection = true;
        viewer.scene.globe.translucency.enabled = false;

        // setTimeout(() => {
        //   this.globeSlider = 50;
        // }, 30);
      } else {
        this.globeSlider = 50;
        viewer.scene.screenSpaceCameraController.enableCollisionDetection = false;
        viewer.scene.globe.translucency.enabled = true;
      }
    },
  },
};
</script>
<style lang="scss" scoped>
.cesium-container {
  width: 100%;
  height: calc(100vh);
  position: relative;
  & > .container {
    width: 100%;
    height: 100%;
  }
  // & > .component-list {
  // }
}
.content {
  position: relative;
}
.globe-slider {
  position: absolute;
  top: 26px;
  right: 5px;
  width: 37px;
  height: 231px;
  padding: 20px 0;
  border-radius: 6px;
  background-color: rgba(0, 0, 0, 0.5);
}
</style>
